<template>
  <div
    class="color-card card"
    :class="{ selected: isSelected, processing: isProcessing }"
    @click="$emit('select')"
  >
    <div class="card-content">
      <!-- 预览图 -->
      <div class="preview-image-full" v-if="firstAvailableAngle">
        <div v-if="getImageUrl(firstAvailableAngle)" class="image-container">
          <img
            :src="getImageUrl(firstAvailableAngle)"
            :alt="`${getColorStyleId(color)}-${getFieldValue(
              color,
              'color_code'
            )}-${getAngleDisplayName(firstAvailableAngle)}`"
            class="preview-image"
            @error="handleImageError"
          />
        </div>
        <div v-else class="image-placeholder-full">
          <span>{{ getAngleDisplayName(firstAvailableAngle) }}</span>
        </div>
      </div>

      <div class="card-details">
        <div class="card-header">
          <div class="card-info">
            <span class="card-title"
              >{{ getColorStyleId(color) }}-{{ getFieldValue(color, 'color_code') }}</span
            >
            <div class="card-subtitle">{{ getFieldValue(color, 'color_name') }}</div>
          </div>

          <span
            class="badge"
            :class="getStatusBadgeClass(getFieldValue(color, 'annotation_status'))"
            >{{ getStatusText(getFieldValue(color, 'annotation_status')) }}</span
          >
        </div>

        <div class="thumbnail-bar">
          <div
            v-for="angle in angleCodes"
            :key="angle"
            class="thumbnail-item"
            :class="{
              missing: (color.missingAngles || []).includes(angle),
              available: (color.angles || []).includes(angle),
            }"
          >
            <span
              v-if="
                (color.angles || []).includes(angle) && !(color.missingAngles || []).includes(angle)
              "
              >{{ getAngleDisplayName(angle) }}</span
            >
            <span v-else>!</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed } from 'vue'
import { getFullImageUrl, handleImageError } from '../utils/imageUtils'
import { getAngleDisplayName } from '../utils/angleUtils'

export default {
  name: 'ColorCard',
  props: {
    color: {
      type: Object,
      required: true,
    },
    isSelected: {
      type: Boolean,
      default: false,
    },
    angleCodes: {
      type: Array,
      default: () => [],
    },
    isProcessing: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['select'],
  setup(props) {
    const getStatusText = status => {
      const statusMap = {
        pending: '待匹配',
        success: '匹配成功',
        failed: '匹配失败',
        empty: '放弃',
        vectoring: '向量中',
        completed: '完成',
      }
      return statusMap[status] || status
    }

    const getStatusBadgeClass = status => {
      const classMap = {
        pending: 'badge-pending',
        success: 'badge-success',
        failed: 'badge-error',
        empty: 'badge-empty',
        vectoring: 'badge-vectoring',
        completed: 'badge-completed',
      }
      return classMap[status] || 'badge-pending'
    }

    // 获取第一个可用的角度
    const firstAvailableAngle = computed(() => {
      const angles = props.color?.angles || []
      if (!angles || angles.length === 0) return null
      return angles[0]
    })

    // 获取图片URL
    const getImageUrl = angle => {
      if (!props.color || !props.color.images) return ''

      const images = props.color.images
      if (!Array.isArray(images)) return ''

      const image = images.find(img => img.angle === angle)
      if (!image) return ''

      const url = image.url
      // 使用工具函数处理图片URL
      return getFullImageUrl(url)
    }

    // 处理图片加载错误
    const handleImageErrorLocal = event => {
      handleImageError(event)
      // 显示占位符
      const placeholder = event.target.parentElement.querySelector('.image-placeholder-full')
      if (placeholder) {
        placeholder.style.display = 'flex'
      }
    }

    // 获取颜色的款式ID
    const getColorStyleId = color => {
      // 适配新的数据结构
      if (color.style_code && typeof color.style_code === 'object' && 'value' in color.style_code) {
        return color.style_code.value || ''
      }
      if (color.style_id && typeof color.style_id === 'object' && 'value' in color.style_id) {
        return color.style_id.value || ''
      }
      return color.style_code || color.style_id || ''
    }

    // 安全地获取字段值（适配新旧数据结构）
    const getFieldValue = (obj, fieldName) => {
      if (!obj || !obj[fieldName]) {
        // 对于数组字段，返回空数组
        if (['angles', 'missingAngles'].includes(fieldName)) {
          return []
        }
        return ''
      }
      const field = obj[fieldName]
      if (typeof field === 'object' && 'value' in field) {
        return field.value || ''
      }
      return field || ''
    }

    return {
      getStatusText,
      getStatusBadgeClass,
      getAngleDisplayName,
      firstAvailableAngle,
      getColorStyleId,
      getFieldValue,
      getImageUrl,
      handleImageError: handleImageErrorLocal,
    }
  },
}
</script>

<style scoped>
.color-card {
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
  padding: 12px;
  width: 100%;
  min-height: 100px;
}

.color-card:hover {
  border-color: var(--primary-color);
}

.color-card.selected {
  border-color: var(--primary-color);
  background: rgba(24, 144, 255, 0.05);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.card-content {
  display: flex;
  gap: 12px;
  height: 100%;
}

.preview-image-full {
  flex-shrink: 0;
  width: 80px;
  height: 100%;
}

.image-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-placeholder-full {
  width: 80px;
  height: 100%;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
  aspect-ratio: 1;
}

.card-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.card-info {
  flex: 1;
  min-width: 0;
  margin-right: 8px;
}

.card-title {
  font-weight: 600;
  display: block;
  margin-bottom: 2px;
}

.card-subtitle {
  font-size: 12px;
  color: var(--text-secondary);
  display: block;
}

.thumbnail-bar {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.thumbnail-item {
  width: 25px;
  height: 25px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 500;
}

.thumbnail-item.available {
  background: var(--success-color);
  color: white;
  border-color: var(--success-color);
}

.thumbnail-item.missing {
  background: #f0f0f0;
  color: var(--text-secondary);
  border-color: #d9d9d9;
}

/* 卡片状态标签样式 */
.badge-pending {
  background: #faad14;
  color: white;
}

.badge-success {
  background: var(--success-color);
  color: white;
}

.badge-error {
  background: var(--error-color);
  color: white;
}

.badge-empty {
  background: #d9d9d9;
  color: var(--text-color);
}

.badge-vectoring {
  background: #722ed1;
  color: white;
}

.badge-completed {
  background: #1890ff;
  color: white;
}

/* 处理中状态样式 - 呼吸式背景渐变 */
.color-card.processing {
  position: relative;
  overflow: hidden;
  animation: breathing 2s ease-in-out infinite;
  border: 2px solid var(--primary-color);
  box-shadow: 0 0 20px rgba(24, 144, 255, 0.3);
}

@keyframes breathing {
  0%,
  100% {
    background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 50%, #f0f8ff 100%);
  }
  50% {
    background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 50%, #e6f7ff 100%);
  }
}

/* 处理中状态下的卡片内容 */
.color-card.processing .card-content {
  position: relative;
  z-index: 2;
}
</style>
